using Digitalmes.Application.Mes.Productions.Consumptions.Commands;
using Digitalmes.Common.Interfaces;
using Digitalmes.Domain.Entities.Mes.Productions;

namespace Digitalmes.Application.Mes.Productions.MaterialLoadings.Commands;

/// <summary>
/// 下料批次料命令。
/// </summary>
/// <param name="Id">批次料上料记录 Id</param>
public sealed record UnloadBatchMaterialLoadingCommand(long Id) : IRequest<IResult<bool>>;

internal sealed class UnloadBatchMaterialLoadingCommandHandler(IRepository<ProdBatchMaterialLoading> repo, ICurrentUser currentUser)
    : IRequestHandler<UnloadBatchMaterialLoadingCommand, IResult<bool>>
{
    public async Task<IResult<bool>> Handle(UnloadBatchMaterialLoadingCommand request, CancellationToken cancellationToken)
    {
        var consumption = await repo.GetByIdAsync(request.Id, cancellationToken);
        if (consumption == null)
        {
            return Result.Failure("未找到上料信息");
        }

        if (consumption.IsUnloading)
        {
            return Result.Failure("批次料已下料");
        }

        consumption.IsUnloading = true;
        consumption.UnloadingBy = currentUser.Username;
        consumption.UnloadingTime = DateTime.Now;
        var ok = await repo.UpdateAsync(consumption, m => new
        {
            m.IsUnloading,
            m.UnloadingBy,
            m.UnloadingTime,
        }, cancellationToken);

        return Result.From(ok);
    }
}
